package com.example.demo.service.impl;

import com.example.demo.dao.BaseDao;
import com.example.demo.domain.base.BaseEntity;
import com.example.demo.service.BaseService;
import com.example.demo.vo.PageRequest;
import com.example.demo.vo.PageResult;
import org.hibernate.criterion.Criterion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

/**
 * @author Jack
 * @Title: 基础服务实现类
 * @Description: 基础服务实现类
 * @date 2018年1月7日14:11:58
 */
@Service
public class BaseServiceImpl<E extends BaseEntity> implements BaseService<E> {

    @Autowired
    @Qualifier("baseDao")
    private BaseDao baseDao;

    protected Class<E> clazz;

    public BaseServiceImpl() {
        Type type = getClass().getGenericSuperclass();
        if (type instanceof ParameterizedType) {
            this.clazz = (Class<E>) ((ParameterizedType) type).getActualTypeArguments()[0];
        } else {
            this.clazz = null;
        }
    }

    public BaseServiceImpl(Class<E> clazz) {
        this.clazz = clazz;
    }


    @Override
    public <E extends BaseEntity> void save(E entity) {
        this.baseDao.save(entity);
    }

    @Override
    public <E extends BaseEntity> void update(E entity) {
        this.baseDao.save(entity);
    }

    @Override
    public <E extends BaseEntity> void saveOrUpdate(E entity) {
        this.baseDao.saveOrUpdate(entity);
    }

    @Override
    public <E extends BaseEntity> E findById(Long id) {
        return this.baseDao.findById((Class<E>) clazz, id);
    }

    @Override
    public <E extends BaseEntity> List<E> findByRestrictions(Criterion... criterion) {
        return this.baseDao.findByRestrictions((Class<E>) clazz, criterion);
    }

    @Override
    public <E extends BaseEntity> PageResult<E> getPage(PageRequest pageRequest, Criterion... criterion) {
        return this.baseDao.getPage((Class<E>) clazz, pageRequest, criterion);
    }

    @Override
    public void deleteByRestrictions(Criterion... criterion) {
        this.baseDao.deleteByRestrictions(clazz, criterion);
    }
}
